package cn.wind.xboot.core.utils;

import cn.wind.xboot.core.res.ApiException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

/**
 * <p>Title: SignUtil</p>
 * <p>Description: TODO</p>
 *
 * @author xukk
 * @version 1.0
 * @date 2018/8/24
 */
public class SignUtil {

    /**
     * md5签名
     *
     * 按参数名称升序，将参数值进行连接 签名
     * @param appSecret
     * @param params
     * @return
     */
    public static String sign(String appSecret, TreeMap<String, String> params) {
        StringBuilder paramValues = new StringBuilder();
        params.put("appSecret", appSecret);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            paramValues.append(entry.getKey()+"="+entry.getValue()+"&");
        }
        paramValues.deleteCharAt(paramValues.length()-1);
        return DigestUtils.md5Hex(paramValues.toString());
    }
    /**
     * 请求参数签名验证
     *
     * @param appSecret
     * @param request
     * @return true 验证通过 false 验证失败
     * @throws Exception
     */
    public static boolean verifySign(String appSecret, HttpServletRequest request) throws Exception {
        TreeMap<String, String> params = new TreeMap<String, String>();
        String signStr = request.getParameter("sign");
        if(StringUtils.isBlank(signStr)){
            throw new ApiException("There is no signature field in the request parameter!");
        }
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String paramName = enu.nextElement().trim();
            if (!paramName.equals("sign")) {
                params.put(paramName, URLDecoder.decode(request.getParameter(paramName), "UTF-8"));
            }
        }

        if (!sign(appSecret, params).equals(signStr)) {
            return false;
        }
        return true;
    }

}
